package com.dayuanit.dy15.atm.controller;

import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.dto.UserDetailDTO;
import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.handler.EmailHandler;
import com.dayuanit.dy15.atm.service.UserDeailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class EmailController extends BaseController {

    @Autowired
    private UserDeailService userDeailService;

    @Autowired
    private EmailHandler emailHandler;

    @RequestMapping("/email/bindEmail.do")
    @ResponseBody
    public ResponseDTO bindEmail(String email, HttpServletRequest request) {
        try {
            //入库成功
            userDeailService.bindEamil(email, getUserId(request));
            //发送邮件
            emailHandler.senndActiveEmail(email);
            return ResponseDTO.sucess();
        } catch (BizException be) {
            be.printStackTrace();
            return ResponseDTO.fail(be.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.fail(e.getMessage());
        }
    }


    @RequestMapping("/email/activeEmail.do")
    public String activeEmail(String email, long expireTime, String sign) {
        //激活的校验问题 安全问题
        //如何防止别人篡改激活地址？ 需要用到消息摘要，一种签名的技术，实现的方式：MD5，SHA

        //明文一样的  得到的签名也是一样的  md5 sha消息摘要算法是不可逆的
        //541641622@qq.com -> md5 -> 签名(abc)
        //541641622@qq.com -> md5 -> 签名(abc)

        userDeailService.activeEmail(email, expireTime, sign);
        return "activeSuccess";
    }


    @RequestMapping("/email/checkBindEmail.do")
    @ResponseBody
    public ResponseDTO checkBindEmail(HttpServletRequest request) {
        UserDetailDTO userDetailDTO = userDeailService.checkBindEmail(getUserId(request));
        return ResponseDTO.sucess(userDetailDTO);
    }

    @RequestMapping("/email/unBindEmail.do")
    @ResponseBody
    public ResponseDTO unBindEmail(HttpServletRequest request) {
        userDeailService.unBindEmail(getUserId(request));
        return ResponseDTO.sucess();
    }


    @RequestMapping("/email/forgetPwd.do")
    @ResponseBody
    public ResponseDTO forgetPwd(String email) {
        //检查邮箱是否被绑定 如果没绑定不发邮件
        try {
            userDeailService.checkBindEmail(email);
            emailHandler.sendForgetPwdEmail(email);
            return ResponseDTO.sucess();
        } catch (BizException be) {
            be.printStackTrace();
            return ResponseDTO.fail(be.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.fail("请联系客服");
        }
    }
}
